package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@EnableScheduling
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;

    @Scheduled(cron = "0 * * * * ? ")
    public void processTimeoutOrders(){
        log.info("定时处理超时订单:{}", LocalDateTime.now());
        List<Orders> byStatusAndOrderTime = orderMapper.getByStatusAndOrderTime(Orders.PENDING_PAYMENT, LocalDateTime.now().plusMinutes(-15));
        if (byStatusAndOrderTime != null && byStatusAndOrderTime.size() > 0){
            for (Orders order : byStatusAndOrderTime) {
                order.setStatus(Orders.CANCELLED);
                order.setCancelReason("支付超时");
                order.setCancelTime(LocalDateTime.now());
                orderMapper.updateOrders(order);
            }
        }
    }

    @Scheduled(cron = "0/5 * * * * ? ")
    public void proccessDeliveryOrder(){
        log.info("定时处理处于待派送状态的订单:{}", LocalDateTime.now());
        List<Orders> byStatusAndOrderTime = orderMapper.getByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS, LocalDateTime.now().plusMinutes(-60));
        if (byStatusAndOrderTime != null && byStatusAndOrderTime.size() > 0){
            for (Orders order : byStatusAndOrderTime) {
                order.setStatus(Orders.COMPLETED);
                orderMapper.updateOrders(order);
            }
        }

    }

}
